#include "filestatusiconmanager.h"
#include <QFileInfo>
#include <QImageReader>
#include <QDebug>
#include <QApplication>
#include <QScreen>
#include <QDir>
#include <QStandardPaths>
#include <QPainterPath>
#include <QLinearGradient>
#include <QRadialGradient>
#include <QFontDatabase>
// 静态成员变量定义
QHash<QString, QIcon> FileStatusIconManager::s_iconCache;
QHash<QString, QPixmap> FileStatusIconManager::s_pixmapCache;
FileStatusIconManager* FileStatusIconManager::instance()
{
    static FileStatusIconManager instance;
    return &instance;
}
QIcon FileStatusIconManager::getIcon(FileStatus status, FileType fileType, int progress, IconSize size)
{
    QString key = generateCacheKey("icon", 
        QString("%1_%2_%3_%4").arg(static_cast<int>(status))
                              .arg(static_cast<int>(fileType))
                              .arg(progress)
                              .arg(static_cast<int>(size)), size);
    if (s_iconCache.contains(key)) {
        return s_iconCache[key];
    }
    QIcon icon = generateIcon(key, size);
    s_iconCache[key] = icon;
    return icon;
}
FileStatusIconManager::FileType FileStatusIconManager::detectFileType(const QString& filePath)
{
    QFileInfo fileInfo(filePath);
    QString suffix = fileInfo.suffix().toLower();
    if (suffix == "pdf") {
        return FileType::PDF;
    } else if (QImageReader::supportedImageFormats().contains(suffix.toLocal8Bit())) {
        return FileType::Image;
    } else if (suffix == "mp4" || suffix == "avi" || suffix == "mov" || suffix == "mkv") {
        return FileType::Video;
    } else if (suffix == "mp3" || suffix == "wav" || suffix == "flac" || suffix == "aac") {
        return FileType::Audio;
    } else if (suffix == "doc" || suffix == "docx" || suffix == "txt" || suffix == "rtf") {
        return FileType::Document;
    }
    return FileType::Unknown;
}
QIcon FileStatusIconManager::createProgressIcon(int progress, IconSize size)
{
    QString key = generateCacheKey("progress", QString::number(progress), size);
    if (s_iconCache.contains(key)) {
        return s_iconCache[key];
    }
    QPixmap pixmap = generateProgressPixmap(progress, size);
    QIcon icon(pixmap);
    s_iconCache[key] = icon;
    return icon;
}
QIcon FileStatusIconManager::getCompletedIcon(FileType fileType, IconSize size)
{
    return getIcon(FileStatus::Completed, fileType, 100, size);
}
QIcon FileStatusIconManager::getErrorIcon(IconSize size)
{
    return getIcon(FileStatus::Error, FileType::Unknown, 0, size);
}
QIcon FileStatusIconManager::getQueuedIcon(IconSize size)
{
    return getIcon(FileStatus::Queued, FileType::Unknown, 0, size);
}
QIcon FileStatusIconManager::getFileTypeIcon(FileType fileType, IconSize size)
{
    return getIcon(FileStatus::Completed, fileType, 100, size);
}
void FileStatusIconManager::clearCache()
{
    s_iconCache.clear();
    s_pixmapCache.clear();
}
int FileStatusIconManager::getCacheSize()
{
    return s_iconCache.size() + s_pixmapCache.size();
}
QIcon FileStatusIconManager::generateIcon(const QString& key, IconSize size)
{
    int sizeInt = static_cast<int>(size);
    QPixmap pixmap(sizeInt, sizeInt);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    // 解析键值获取参数
    QStringList parts = key.split('_');
    if (parts.size() >= 4) {
        FileStatus status = static_cast<FileStatus>(parts[1].toInt());
        FileType fileType = static_cast<FileType>(parts[2].toInt());
        int progress = parts[3].toInt();
        QRect rect(0, 0, sizeInt, sizeInt);
        if (status == FileStatus::Processing && progress > 0) {
            // 绘制进度图标
            drawProgressPie(painter, rect, progress);
        } else if (status == FileStatus::Completed) {
            // 绘制完成状态 + 文件类型
            drawStatusIcon(painter, rect, status);
            drawFileTypeIcon(painter, rect, fileType);
        } else {
            // 绘制状态图标
            drawStatusIcon(painter, rect, status);
        }
    }
    return QIcon(pixmap);
}
QPixmap FileStatusIconManager::generateProgressPixmap(int progress, IconSize size)
{
    int sizeInt = static_cast<int>(size);
    QPixmap pixmap(sizeInt, sizeInt);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    QRect rect(0, 0, sizeInt, sizeInt);
    drawProgressPie(painter, rect, progress);
    return pixmap;
}
QPixmap FileStatusIconManager::generateFileTypePixmap(FileType fileType, IconSize size)
{
    int sizeInt = static_cast<int>(size);
    QPixmap pixmap(sizeInt, sizeInt);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    QRect rect(0, 0, sizeInt, sizeInt);
    drawFileTypeIcon(painter, rect, fileType);
    return pixmap;
}
QPixmap FileStatusIconManager::generateStatusPixmap(FileStatus status, IconSize size)
{
    int sizeInt = static_cast<int>(size);
    QPixmap pixmap(sizeInt, sizeInt);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    QRect rect(0, 0, sizeInt, sizeInt);
    drawStatusIcon(painter, rect, status);
    return pixmap;
}
QString FileStatusIconManager::generateCacheKey(const QString& type, const QString& name, IconSize size)
{
    return QString("%1_%2_%3").arg(type).arg(name).arg(static_cast<int>(size));
}
void FileStatusIconManager::drawProgressPie(QPainter& painter, const QRect& rect, int progress)
{
    // 设置颜色
    QColor primaryColor = getPrimaryColor();
    QColor mutedColor = getMutedColor();
    // 绘制背景圆
    painter.setBrush(QBrush(mutedColor));
    painter.setPen(QPen(mutedColor, 1));
    painter.drawEllipse(rect);
    // 绘制进度饼图
    if (progress > 0) {
        painter.setBrush(QBrush(primaryColor));
        painter.setPen(QPen(primaryColor, 1));
        int startAngle = 90 * 16; // 从顶部开始
        int spanAngle = -progress * 3.6 * 16; // 顺时针绘制
        painter.drawPie(rect, startAngle, spanAngle);
    }
    // 绘制进度文字（大图标时）
    if (rect.width() >= 24) {
        painter.setPen(QPen(Qt::white, 2));
        QFont font = painter.font();
        font.setPointSize(rect.width() / 5);
        font.setBold(true);
        painter.setFont(font);
        QString text = QString("%1%").arg(progress);
        painter.drawText(rect, Qt::AlignCenter, text);
    }
}
void FileStatusIconManager::drawFileTypeIcon(QPainter& painter, const QRect& rect, FileType fileType)
{
    QColor iconColor = getPrimaryColor();
    painter.setPen(QPen(iconColor, 2));
    painter.setBrush(QBrush(iconColor));
    int centerX = rect.center().x();
    int centerY = rect.center().y();
    int radius = qMin(rect.width(), rect.height()) / 3;
    switch (fileType) {
        case FileType::PDF: {
            // 绘制PDF图标 - 文档形状
            painter.drawRect(centerX - radius/2, centerY - radius, radius, radius);
            painter.drawLine(centerX - radius/2, centerY - radius/2, centerX + radius/2, centerY - radius/2);
            painter.drawLine(centerX - radius/2, centerY, centerX + radius/2, centerY);
            break;
        }
        case FileType::Image: {
            // 绘制图片图标 - 山形
            QPainterPath path;
            path.moveTo(centerX - radius, centerY + radius/2);
            path.lineTo(centerX - radius/2, centerY - radius/2);
            path.lineTo(centerX, centerY);
            path.lineTo(centerX + radius/2, centerY - radius/2);
            path.lineTo(centerX + radius, centerY + radius/2);
            painter.drawPath(path);
            break;
        }
        case FileType::Video: {
            // 绘制视频图标 - 播放按钮
            QPainterPath playPath;
            playPath.moveTo(centerX - radius/2, centerY - radius/2);
            playPath.lineTo(centerX + radius/2, centerY);
            playPath.lineTo(centerX - radius/2, centerY + radius/2);
            playPath.closeSubpath();
            painter.drawPath(playPath);
            break;
        }
        case FileType::Audio: {
            // 绘制音频图标 - 音符
            painter.drawEllipse(centerX - radius/3, centerY - radius/3, radius/3, radius/3);
            painter.drawLine(centerX, centerY - radius/2, centerX, centerY + radius/2);
            painter.drawLine(centerX, centerY - radius/2, centerX + radius/2, centerY - radius/4);
            painter.drawLine(centerX, centerY + radius/2, centerX + radius/2, centerY + radius/4);
            break;
        }
        case FileType::Document: {
            // 绘制文档图标 - 文本
            painter.drawRect(centerX - radius/2, centerY - radius, radius, radius);
            painter.drawLine(centerX - radius/3, centerY - radius/3, centerX + radius/3, centerY - radius/3);
            painter.drawLine(centerX - radius/3, centerY, centerX + radius/3, centerY);
            painter.drawLine(centerX - radius/3, centerY + radius/3, centerX + radius/3, centerY + radius/3);
            break;
        }
        default: {
            // 绘制通用文件图标
            painter.drawRect(centerX - radius/2, centerY - radius, radius, radius);
            break;
        }
    }
}
void FileStatusIconManager::drawStatusIcon(QPainter& painter, const QRect& rect, FileStatus status)
{
    QColor statusColor;
    int centerX = rect.center().x();
    int centerY = rect.center().y();
    int radius = qMin(rect.width(), rect.height()) / 3;
    switch (status) {
        case FileStatus::Queued:
            statusColor = getMutedColor();
            // 绘制时钟图标
            painter.setPen(QPen(statusColor, 2));
            painter.drawEllipse(centerX - radius, centerY - radius, radius*2, radius*2);
            painter.drawLine(centerX, centerY, centerX, centerY - radius/2);
            painter.drawLine(centerX, centerY, centerX + radius/2, centerY);
            break;
        case FileStatus::Processing:
            statusColor = getPrimaryColor();
            // 绘制旋转箭头
            painter.setPen(QPen(statusColor, 2));
            painter.drawArc(centerX - radius, centerY - radius, radius*2, radius*2, 0, 270*16);
            break;
        case FileStatus::Completed:
            statusColor = getSuccessColor();
            // 绘制对勾
            painter.setPen(QPen(statusColor, 2));
            painter.drawLine(centerX - radius/2, centerY, centerX - radius/4, centerY + radius/4);
            painter.drawLine(centerX - radius/4, centerY + radius/4, centerX + radius/2, centerY - radius/2);
            break;
        case FileStatus::Error:
            statusColor = getErrorColor();
            // 绘制X
            painter.setPen(QPen(statusColor, 2));
            painter.drawLine(centerX - radius/2, centerY - radius/2, centerX + radius/2, centerY + radius/2);
            painter.drawLine(centerX + radius/2, centerY - radius/2, centerX - radius/2, centerY + radius/2);
            break;
    }
}
QColor FileStatusIconManager::getPrimaryColor()
{
    return QColor(0, 122, 255); // 系统蓝
}
QColor FileStatusIconManager::getSuccessColor()
{
    return QColor(52, 199, 89); // 成功绿
}
QColor FileStatusIconManager::getWarningColor()
{
    return QColor(255, 149, 0); // 警告橙
}
QColor FileStatusIconManager::getErrorColor()
{
    return QColor(255, 59, 48); // 错误红
}
QColor FileStatusIconManager::getMutedColor()
{
    return QColor(142, 142, 147); // 次要灰
}
